# !/user/bin/env python
# -*- coding:utf-8 -*-
import numpy as np
import os
import sys
import pandas as pd
os.chdir('C:/Users/admin/Desktop')
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
pd.set_option('mode.chained_assignment', None)
f = pd.read_csv('down_otu_tax.txt',header=0,sep='\t',error_bad_lines=False)
f.loc[f['taxonomy']=='None','taxonomy']='k__others'
def absolute(n,level,filename):
    taxName = pd.DataFrame((';'.join(x.split('; ')[0:n]) for x in f['taxonomy']),index = f.index,columns = ['tax_name'])
    data = f.drop(['taxonomy','OTU ID'],axis=1)
    df = pd.merge(taxName,data,right_index=True,left_index=True)
    dfSum = df.groupby(['tax_name']).agg('sum')
    taxLevelName = [x.split(';')[-1] for x in dfSum.index]
    taxLevel = [x.split('__')[0] for x in taxLevelName]
    taxName = [x.split('__')[1] for x in taxLevelName]
    tax_level_name = pd.DataFrame({'tax_level':taxLevel,'Taxonomy':taxName},index=dfSum.index)
    tax_level_name.loc[tax_level_name['tax_level'] != level,'Taxonomy'] = 'others'
    tax_level_name = tax_level_name.drop(['tax_level'],axis=1)
    tax = pd.merge(tax_level_name,dfSum,right_index=True,left_index=True)
    tax = tax.reset_index()
    tax.loc[tax['Taxonomy'] == 'others','tax_name']='others'
    tax = tax.set_index(['Taxonomy'])
    tax1= tax.groupby('Taxonomy')['tax_name'].sum()
    tax2 = tax.groupby('Taxonomy').sum()
    tax3 = pd.merge(tax2,tax1,right_index=True,left_index=True)
    tax4 = tax3.drop(['tax_name'],axis=1)
    tax5 = tax4.drop(['others'],axis=0)
    tax5['Col_sum'] = tax5.apply(lambda x: x.sum(), axis=1)
    tax5 = tax5.sort_values(by='Col_sum',ascending=False)
    tax5 = tax5.drop(['Col_sum'],axis=1)
    tax5.loc[:,'Tax_detail'] = tax3['tax_name']
    tax5.loc['others',:] = tax4.loc['others']
    tax5.to_csv(filename,sep='\t')
#absolute(1,'k','otu_table.k.absolute.txt')
absolute(2,'p','otu_table.p.absolute.xls')
absolute(3,'c','otu_table.c.absolute.xls')
absolute(4,'o','otu_table.o.absolute.xls')
absolute(5,'f','otu_table.f.absolute.xls')
absolute(6,'g','otu_table.g.absolute.xls')
